from pptx import Presentation
from docx.shared import Pt
from pptx.dml.color import RGBColor
from datetime import datetime
import tools
import sys

def handle_texts(texts):
    temp = []
    for text in texts:
        if text == '\n' or text == '':continue
        text = tools.handle_text(text,fromLan)
        temp.append(text+"\n")
    return temp

def handle_wait_tran(wait_tran):
    temp = []
    for ttext in wait_tran:
        ttext = ttext.replace(" ", '')
        temp.append(tools.tran(ttext,fromLan,toLan,appid,appkey) + "\n")
    return temp

def get_font(p):
    font = {
        'name':p.runs[0].font.name,
        'size':p.runs[0].font.size,
        'color':RGBColor(0, 0, 0)
    }
    try:
        font['color'] = p.runs[0].font.color.rgb
    except Exception as e:
        font['color'] = RGBColor(0, 0, 0)
        pass
    #print(p.runs[0].text, font)
    return font

def get_txt():
    page = 1
    with open(resfilename, 'w', encoding='utf-8') as file:
        for slide in ppt.slides:
            sortedShapes = sorted(slide.shapes, key=lambda x: (x.top, x.left))  # 给各个shape排序
            print(f"***************************************{page}*****************************************\n")
            file.write(f"***************************************{page}*****************************************\n")
            for shape in sortedShapes:
                if hasattr(shape, "shapes"):
                    for child_shape in shape.shapes:
                        if child_shape.has_text_frame:
                            text_frame = child_shape.text_frame
                            for paragraph in text_frame.paragraphs:
                                txt = paragraph.text
                                file.write(txt + '\n')
                                #file.write('----------------------shape--------------------\n')

                if shape.has_text_frame:
                    text_frame = shape.text_frame
                    for paragraph in text_frame.paragraphs:
                        txt = paragraph.text
                        txt = tools.handle_text(txt,fromLan)
                        if tools.jump_text(txt): continue
                        file.write(txt + '\n')
                        #file.write('----------------------shape--------------------\n')
                if shape.has_table:
                    continue
                    table = shape.table
                    file.write("----------------------表格----------------------\n")
                    for row in range(len(table.rows)):
                        for col in range(len(table.columns)):
                            text_frame = table.cell(row, col).text_frame
                            for paragraph in text_frame.paragraphs:
                                txt = tools.handle_text(paragraph.text,fromLan)
                                if tools.jump_text(txt): continue
                                print(txt)
                                file.write(txt + '\n')
                        #file.write("=====行=====\n")
            page += 1

def direct_tran_pptx():
    page = 1
    with open(resfilename, 'w',encoding='utf-8') as file:
        try:
            for slide in ppt.slides:
                sortedShapes = sorted(slide.shapes, key=lambda x: (x.top, x.left))#给各个shape排序
                print(f"***************************************{page}*****************************************\n")
                file.write(f"***************************************{page}*****************************************\n")
                for shape in sortedShapes:

                    if hasattr(shape, "shapes"):  # 6表示组合形状(GroupShape)
                        for child_shape in shape.shapes:
                            if child_shape.has_text_frame:
                                text_frame = child_shape.text_frame
                                for paragraph in text_frame.paragraphs:
                                    txt = paragraph.text
                                    if tools.jump_text(txt): continue
                                    txt_tran = tools.tran(txt, fromLan, toLan, appid, appkey)
                                    print(txt)
                                    file.writelines([txt + '\n', txt_tran + '\n'])

                                    '''修改pptx'''
                                    paragraph.text =  txt_tran
                                    font = get_font(paragraph)
                                    paragraph.font.name = 'Times New Roman'
                                    paragraph.font.size = Pt(text_size)
                                    paragraph.font.color.rgb = font['color']
                                    file.write('----------------------shape--------------------\n')

                    if shape.has_text_frame:
                        text_frame = shape.text_frame
                        for paragraph in text_frame.paragraphs:
                            txt = paragraph.text
                            if tools.jump_text(txt):continue
                            txt_tran = tools.tran(txt,fromLan,toLan,appid,appkey)
                            print(txt)
                            file.writelines([txt+'\n',txt_tran + '\n'])

                            '''修改pptx'''
                            paragraph.text = txt_tran
                            font = get_font(paragraph)
                            paragraph.font.name = 'Times New Roman'
                            paragraph.font.size = Pt(text_size)
                            paragraph.font.color.rgb = font['color']
                            file.write('----------------------shape--------------------\n')

                    if shape.has_table:
                        continue
                        table = shape.table
                        file.write("----------------------表格----------------------\n")
                        for row in range(len(table.rows)):
                            for col in range(len(table.columns)):
                                text_frame = table.cell(row, col).text_frame
                                for paragraph in text_frame.paragraphs:
                                    txt = tools.handle_text(paragraph.text,fromLan)
                                    if tools.jump_text(txt): continue
                                    print(txt)
                                    txt_tran = tools.tran(txt, fromLan, toLan,appid,appkey)
                                    paragraph.text = txt_tran
                                    #paragraph.font.name = 'Times New Roman'
                                    paragraph.font.size = Pt(table_size)
                                    file.writelines([txt+'\n',txt_tran + '\n'])
                            file.write("=====行=====\n")
                page += 1
            ppt.save(f'机翻-{name}.pptx')
        except Exception as e:
            print(e)
            ppt.save(f'机翻-{name}.pptx')


def tran_pptx():
    page = 1
    with open(resfilename, 'w', encoding='utf-8') as file:
        try:
            for slide in ppt.slides:
                sortedShapes = sorted(slide.shapes, key=lambda x: (x.top, x.left))  # 给各个shape排序
                print(f"***************************************{page}*****************************************\n")
                file.write(f"***************************************{page}*****************************************\n")
                for shape in sortedShapes:

                    if hasattr(shape, "shapes"):  # 6表示组合形状(GroupShape)
                        for child_shape in shape.shapes:
                            if child_shape.has_text_frame:
                                text_frame = child_shape.text_frame
                                for paragraph in text_frame.paragraphs:
                                    txt = paragraph.text
                                    if tools.jump_text(txt): continue
                                    txt_tran = tools.tran(txt, fromLan, toLan, appid, appkey)
                                    print(txt)
                                    file.writelines([txt + '\n', txt_tran + '\n'])

                                    '''修改pptx'''
                                    paragraph.text = txt + "\n" + txt_tran
                                    font = get_font(paragraph)
                                    paragraph.font.name = 'Times New Roman'
                                    paragraph.font.size = Pt(text_size)
                                    paragraph.font.color.rgb = font['color']
                                    file.write('----------------------shape--------------------\n')

                    if shape.has_text_frame:
                        text_frame = shape.text_frame
                        for paragraph in text_frame.paragraphs:
                            txt = paragraph.text
                            if tools.jump_text(txt): continue
                            txt_tran = tools.tran(txt, fromLan, toLan, appid, appkey)
                            print(txt)
                            file.writelines([txt + '\n', txt_tran + '\n'])

                            '''修改pptx'''
                            paragraph.text = txt + "\n" + txt_tran
                            font = get_font(paragraph)
                            paragraph.font.name = 'Times New Roman'
                            paragraph.font.size = Pt(text_size)
                            paragraph.font.color.rgb = font['color']
                            file.write('----------------------shape--------------------\n')

                    if shape.has_table:
                        table = shape.table
                        file.write("----------------------表格----------------------\n")
                        for row in range(len(table.rows)):
                            for col in range(len(table.columns)):
                                text_frame = table.cell(row, col).text_frame
                                for paragraph in text_frame.paragraphs:
                                    txt = tools.handle_text(paragraph.text, fromLan)
                                    if tools.jump_text(txt): continue
                                    print(txt)
                                    txt_tran = tools.tran(txt, fromLan, toLan, appid, appkey)
                                    paragraph.text = txt + "\n" + txt_tran
                                    # paragraph.font.name = 'Times New Roman'
                                    paragraph.font.size = Pt(table_size)
                                    file.writelines([txt + '\n', txt_tran + '\n'])
                            file.write("=====行=====\n")
                page += 1
            ppt.save(f'机翻-{name}.pptx')
        except Exception as e:
            print(e)
            ppt.save(f'机翻-{name}.pptx')

def get_txt_and_tran_section():
    page = 1
    with open(resfilename, 'w', encoding='utf-8') as file:
        for slide in ppt.slides:
            sortedShapes = sorted(slide.shapes, key=lambda x: (x.top, x.left))  # 给各个shape排序
            print(f"***************************************{page}*****************************************\n")
            file.write(f"***************************************{page}*****************************************\n")
            for shape in sortedShapes:
                if hasattr(shape, 'text'):
                    txt = shape.text_frame.text
                    texts = handle_texts(txt.split("\n"))
                    if len(texts) <= 0: continue
                    print(texts)
                    file.writelines(texts)
                    wait_tran = handle_wait_tran(texts)
                    file.writelines(wait_tran)
                    file.write('----------------------shape--------------------\n')
                if shape.has_table:
                    table = shape.table
                    file.write("----------------------表格----------------------\n")
                    for row in range(len(table.rows)):
                        for col in range(len(table.columns)):
                            text_frame = table.cell(row, col).text_frame
                            for paragraph in text_frame.paragraphs:
                                txt = tools.handle_text(paragraph.text,fromLan)
                                if tools.jump_text(txt): continue
                                print(txt)
                                file.writelines([txt+'\n',tools.tran(txt, fromLan, toLan,appid,appkey) + '\n'])
                        file.write("=====行=====\n")
            page += 1

#逐句翻译
def get_txt_and_tran_each():
    page = 1
    with open(resfilename, 'w', encoding='utf-8') as file:
        for slide in ppt.slides:
            sortedShapes = sorted(slide.shapes, key=lambda x: (x.top, x.left))  # 给各个shape排序
            print(f"***************************************{page}*****************************************\n")
            file.write(f"***************************************{page}*****************************************\n")
            for shape in sortedShapes:
                if hasattr(shape, 'text'):
                    content = shape.text_frame.text
                    texts = handle_texts(content.split("\n"))
                    if len(texts) <= 0: continue
                    for txt in texts:
                        if tools.jump_text(txt): continue
                        print(txt)
                        file.writelines([txt + '\n', tools.tran(txt,fromLan,toLan,appid,appkey) + '\n'])
                if shape.has_table:
                    table = shape.table
                    file.write("----------------------表格----------------------\n")
                    for row in range(len(table.rows)):
                        for col in range(len(table.columns)):
                            text_frame = table.cell(row, col).text_frame
                            for paragraph in text_frame.paragraphs:
                                txt = tools.handle_text(paragraph.text,fromLan)
                                if tools.jump_text(txt): continue
                                print(txt)
                                file.writelines([txt + '\n', tools.tran(txt, fromLan, toLan,appid,appkey) + '\n'])
                        file.write("=====行=====\n")
            page += 1

if __name__ == "__main__":
    s = datetime.now()

    print('1.双语ppt')
    print('2.提取纯文本')
    print('3.双语整段')
    print('4.逐句双语')
    print('5.纯译文ppt')
    action = int(input('请输入你的操作:'))

    if action !=2:
        '''获取appid 和 appkey'''
        idkey = tools.getidkey()
        appid = idkey[0]
        appkey = idkey[1]
        fromLan, toLan = tools.getLanguage()
        text_size = 12
        table_size = 9
    fromLan = 'en'
    files = tools.getFilesList('pptx')
    if len(files)<=0:
        print('没有找到pptx文件')
        input('按任意键退出...')
        sys.exit(0)

    file = files[0]
    name = file.split('.')[0]

    filename = f'{name}.pptx'
    ppt = Presentation(filename)

    if action == 1:
        resfilename = f'机翻-{name}.txt'
        tran_pptx() # 翻译pptx，译文直接写入ppt
    elif action ==2:
        resfilename = f'文本-{name}.txt'
        get_txt() # 提取纯文本
    elif action ==3:
        resfilename = f'双语整段-{name}.txt'
        get_txt_and_tran_section() # 双语整段
    elif action ==4:
        resfilename = f'逐句双语-{name}.txt'
        get_txt_and_tran_each() # 逐句双语
    elif action ==5:
        resfilename = f'逐句双语-{name}.txt'
        direct_tran_pptx() # 逐句双语
    else:
        print("操作错误！")

    print(f"完成！共计:{tools.diff_time(s, datetime.now())}分钟")
    input('按任意键退出...')